package cn.bass.marketing.service.strategy.impl;

import cn.bass.marketing.common.constant.RedisConstant;
import cn.bass.marketing.common.enums.StatusEnums;
import cn.bass.marketing.common.exception.AppException;
import cn.bass.marketing.common.vo.resp.MarketingStrategyRespVO;
import cn.bass.marketing.convertor.MarketingStrategyConvertor;
import cn.bass.marketing.entity.MarketingStrategyDO;
import cn.bass.marketing.mapper.MarketingStrategyMapper;
import cn.bass.marketing.redis.core.IRedisService;
import cn.bass.marketing.service.strategy.MarketingStrategyService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * {@author}: LiuWei
 * {@version}: 1.0
 * {@since}: 2024-08-15
 * {@link}: cn.bass.marketing.common.constant.RulesConstant
 * 描述：策略服务接口实现类
 */
@Slf4j
@Service
public class MarketingStrategyServiceImp extends ServiceImpl<MarketingStrategyMapper, MarketingStrategyDO> implements MarketingStrategyService {

    @Resource
    private IRedisService redisService;

    /**
     * 根据策略id查询策略信息
     *
     * @param strategyId
     * @return
     */
    @Override
    public MarketingStrategyRespVO selectById(String strategyId) {
        // 从redis中获取策略信息
        String strategyKey = String.format(RedisConstant.MARKETING_STRATEGY, strategyId);
        MarketingStrategyRespVO strategyRespVO = redisService.getValue(strategyKey);
        if (strategyRespVO != null) {
            return strategyRespVO;
        }

        // 从数据库中获取策略信息
        LambdaQueryWrapper<MarketingStrategyDO> marketingStrategyWrapper = Wrappers.lambdaQuery();
        marketingStrategyWrapper.eq(MarketingStrategyDO::getCStrategyId, strategyId);
        marketingStrategyWrapper.eq(MarketingStrategyDO::getCStatus, StatusEnums.ENABLED.getStatusType());
        marketingStrategyWrapper.last("LIMIT 1");
        MarketingStrategyDO marketingStrategyDO = this.baseMapper.selectOne(marketingStrategyWrapper);
        if (marketingStrategyDO == null) {
            log.error("策略id:{}不存在或已被删除", strategyId);
            throw new AppException("策略id:" + strategyId + "不存在或已被删除");
        }
        MarketingStrategyRespVO marketingStrategyRespVO = MarketingStrategyConvertor.INSTANCE.do2respVO(marketingStrategyDO);
        // 将策略信息存入redis
        redisService.setValue(strategyKey, marketingStrategyRespVO);
        return marketingStrategyRespVO;
    }
}
